#pragma once

#include <iostream>
#include <sys/epoll.h>
#include <memory>
#include "Sockets.hpp"
#include "Epoller.hpp"
#include "nocopy.hpp"

using namespace std;

class EpollServer : public nocopy
{
    static const int num = 64;
public:
    EpollServer(uint16_t port)
        : _port(port)
        , _listensock_ptr(new Sockets())
        , _epoller_ptr(new Epoller())
    {}

    void Init()
    {
        _listensock_ptr->Socket();
        _listensock_ptr->Bind(_port);
        _listensock_ptr->Listen();

        log(Info, "create listen socket success: %d\n", _listensock_ptr->Fd());
    }

    void Start()
    {
        _epoller_ptr->EpollCtl(EPOLL_CTL_ADD, _listensock_ptr->Fd(), EPOLLIN);
        struct epoll_event revs[num];

        for(;;)
        {
            int n = _epoller_ptr->EpollWait(revs, num);
            if(n > 0)
            {
                Dispatcher(revs, n);
            }
            else if(n == 0)
            {
                cout << "time out..." << endl;
            }
            else
            {
                log(Error, "epoll wait error!!!");
                exit(0);
            }
        }
    }

    void Dispatcher(struct epoll_event revs[], int num)
    {
        for(int i = 0; i < num; i++)
        {
            uint32_t event = revs[i].events;
            int fd = revs[i].data.fd;

            if(event & EPOLLIN)
            {
                if(fd == _listensock_ptr->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(fd);
                }
            }
            else if(event & EPOLLOUT)
            {}
            else
            {}
        }
    }

    void Accepter()
    {
        string clientip;
        uint16_t clientport;
        int sock = _listensock_ptr->Accept(&clientip, &clientport);
        if(sock > 0)
        {
            _epoller_ptr->EpollCtl(EPOLL_CTL_ADD, sock, EPOLLIN);
            log(Info, "get a new link, client info@ %s:%d", clientip.c_str(), clientport);
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "get a messge: " << buffer;
        }
        else if(n == 0)
        {
            log(Info, "client quit, me too, close fd is : %d", fd);
            _epoller_ptr->EpollCtl(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            log(Warning, "recv error, fd is : %d", fd);
            _epoller_ptr->EpollCtl(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

    ~EpollServer()
    {
        _listensock_ptr->Close();
    }

private:
    shared_ptr<Sockets> _listensock_ptr;
    shared_ptr<Epoller> _epoller_ptr;
    uint16_t _port;
};